import tkinter as tk
from tkinter import ttk,Text
from tkinter import messagebox
from datetime import datetime
from tkcalendar import DateEntry
import pandas as pd
from setting import Setting

class Tenant:
    def __init__(self):
        self.setting = Setting()
        self.url_fileRoomInfo = self.setting.url_fileRoomInfo
        self.url_fileTenantInfo = self.setting.url_fileTenantInfo

    def frame2TenantShow(self): #在租客信息页展示租客信息，可重复调用，调用后会进行覆盖
        df = pd.read_excel(self.url_fileTenantInfo, sheet_name='Tenant', engine='openpyxl', header=0)
        #取得数据后按房间排序
        df = df.sort_values(by=df.columns[0], ascending=True)
        line = len(df)
        # 清空数据
        self.canvas2.delete(*self.canvas2.get_children())
        for i in range(line):
            self.canvas2.insert("", "end", values=(df.iloc[i, 0], df.iloc[i, 1], df.iloc[i, 2], df.iloc[i, 3],
                                                   df.iloc[i, 4], df.iloc[i, 5], df.iloc[i, 6], df.iloc[i, 7],
                                                   df.iloc[i, 8], df.iloc[i, 9], df.iloc[i, 10]))

    def tenantManger(self, frame2):#租客管理
        """设置布局"""
        canvas1 = tk.Canvas(frame2, width=500, height=300)
        canvas1.pack(side=tk.TOP)
        canvas = tk.Canvas(frame2, width=500, height=10, bg="blue")#, bg="blue"
        canvas.pack()
        canvas3 = tk.Canvas(frame2, width=500, height=400)#, bg="red"
        canvas3.pack()#side=tk.BOTTOM
        """设置查询管理"""
        LabelTitler = ttk.Label(canvas1, text="房间号", relief="solid", padding=(4, 4), width=10, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=0)
        self.enTroomid = ttk.Entry(canvas1, width=12)
        self.enTroomid.grid(row=1, column=0, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="租客姓名", relief="solid", padding=(4, 4), width=10, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=1)
        self.enTtenant = ttk.Entry(canvas1, width=12)
        self.enTtenant.grid(row=1, column=1, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="身份证号", relief="solid", padding=(4, 4), width=16, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=2)
        self.enTid = ttk.Entry(canvas1, width=16)
        self.enTid.grid(row=1, column=2, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="电话", relief="solid", padding=(4, 4), width=10, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=3)
        self.enTphone = ttk.Entry(canvas1, width=12)
        self.enTphone.grid(row=1, column=3, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="首租时间", relief="solid", padding=(4, 4), width=12, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=4)
        self.enTcheckintime = DateEntry(canvas1, date_pattern='YYYY-MM-DD', width=12)
        self.enTcheckintime.grid(row=1, column=4, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="租金", relief="solid", padding=(4, 4), width=4, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=5)
        self.enTamount = ttk.Entry(canvas1, width=4)
        self.enTamount.grid(row=1, column=5, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="押金", relief="solid", padding=(4, 4), width=4, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=6)
        self.enTdeposit = ttk.Entry(canvas1, width=4)
        self.enTdeposit.grid(row=1, column=6, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="水表1底", relief="solid", padding=(4, 4), width=6, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=7)
        self.enTwarter1 = ttk.Entry(canvas1, width=6)
        self.enTwarter1.grid(row=1, column=7, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="水表2底", relief="solid", padding=(4, 4), width=6, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=8)
        self.enTwarter2 = ttk.Entry(canvas1, width=6)
        self.enTwarter2.grid(row=1, column=8, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="电表1底", relief="solid", padding=(4, 4), width=6, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=9)
        self.enTelectric1 = ttk.Entry(canvas1, width=6)
        self.enTelectric1.grid(row=1, column=9, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="电表2底", relief="solid", padding=(4, 4), width=6, font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=10)
        self.enTelectric2 = ttk.Entry(canvas1, width=6)
        self.enTelectric2.grid(row=1, column=10, sticky='nsew')

        hpBtn4 = ttk.Button(canvas1, text="查找", command=self.findtenant)
        hpBtn4.grid(row=2, column=0, columnspan=2, sticky='nsew')
        hpBtn1 = ttk.Button(canvas1, text="添加", command=self.addtenant)
        hpBtn1.grid(row=3, column=0, sticky='nsew')
        hpBtn2 = ttk.Button(canvas1, text="修改", command=self.modifytenant)
        hpBtn2.grid(row=3, column=1, sticky='nsew')
        hpBtn3 = ttk.Button(canvas1, text="删除", command=self.deltenant)
        hpBtn3.grid(row=4, column=0, columnspan=2, sticky='nsew')
        #设置表头
        self.canvas2 = ttk.Treeview(canvas3, columns=("roomid", "tenant", "id", "phone", "checkintime", "amount", "deposit",
                                                      "warter1", "warter2", "electric1", "electric2"), show="headings")
        self.canvas2.heading("roomid", text="房间号")
        self.canvas2.heading("tenant", text="租客姓名")
        self.canvas2.heading("id", text="身份证号")
        self.canvas2.heading("phone", text="电话")
        self.canvas2.heading("checkintime", text="首租时间")
        self.canvas2.heading("amount", text="租金")
        self.canvas2.heading("deposit", text="押金")
        self.canvas2.heading("warter1", text="水表1底")
        self.canvas2.heading("warter2", text="水表2底")
        self.canvas2.heading("electric1", text="电表1底")
        self.canvas2.heading("electric2", text="电表2底")
        #设置列宽
        self.canvas2.column("roomid", width=60, anchor='center')
        self.canvas2.column("tenant", width=70, anchor='center')
        self.canvas2.column("id", width=160)
        self.canvas2.column("phone", width=110)
        self.canvas2.column("checkintime", width=100)
        self.canvas2.column("amount", width=60, anchor='center')
        self.canvas2.column("deposit", width=60, anchor='center')
        self.canvas2.column("warter1", width=60, anchor='center')
        self.canvas2.column("warter2", width=60, anchor='center')
        self.canvas2.column("electric1", width=60, anchor='center')
        self.canvas2.column("electric2", width=60, anchor='center')
        self.canvas2.pack(side=tk.LEFT)

        scrollbar = tk.Scrollbar(canvas3, orient="vertical", command=self.canvas2.yview())
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.canvas2.configure(yscrollcommand=scrollbar.set)

        self.frame2TenantShow()

    def addtenant(self): #添加租客
        roomid = self.enTroomid.get()
        tenant = self.enTtenant.get()
        id = self.enTid.get()
        phone = self.enTphone.get()
        checkintime = self.enTcheckintime.get()
        amount = self.enTamount.get()
        deposit = self.enTdeposit.get()
        warter1 = self.enTwarter1.get()
        warter2 = self.enTwarter2.get()
        electric1 = self.enTelectric1.get()
        electric2 = self.enTelectric2.get()
        lineText = self.setting.roomList(self.url_fileTenantInfo, 'Tenant') #获取已维护租客信息表里的房间信息
        roomList = self.setting.roomList(self.url_fileRoomInfo, 'RoomInfo') #获取已有房间清单
        if roomid in lineText:
            messagebox.showwarning("告警", "租客信息已存在！")
        elif roomid not in roomList:
            messagebox.showwarning("告警", "房间不存在！")
        else:
            df = pd.read_excel(self.url_fileTenantInfo, sheet_name='Tenant', engine='openpyxl', header=None)
            row_index = len(df)
            df.loc[row_index + 1, 0] = roomid
            df.loc[row_index + 1, 1] = tenant
            df.loc[row_index + 1, 2] = id
            df.loc[row_index + 1, 3] = phone
            df.loc[row_index + 1, 4] = checkintime
            df.loc[row_index + 1, 5] = amount
            df.loc[row_index + 1, 6] = deposit
            df.loc[row_index + 1, 7] = warter1
            df.loc[row_index + 1, 8] = warter2
            df.loc[row_index + 1, 9] = electric1
            df.loc[row_index + 1, 10] = electric2
            #print(df)
            # 将DataFrame对象写入特定的工作表和行
            df.to_excel(self.url_fileTenantInfo, index=False, header=False, sheet_name='Tenant', startrow=0)
            self.frame2TenantShow() #重新展示租客户信息

    def modifytenant(self): #修改租客信息
        roomid = self.enTroomid.get()
        tenant = self.enTtenant.get()
        id = self.enTid.get()
        phone = self.enTphone.get()
        checkintime = self.enTcheckintime.get()
        amount = self.enTamount.get()
        deposit = self.enTdeposit.get()
        warter1 = self.enTwarter1.get()
        warter2 = self.enTwarter2.get()
        electric1 = self.enTelectric1.get()
        electric2 = self.enTelectric2.get()
        lineText = self.setting.roomList(self.url_fileTenantInfo, 'Tenant') #获取已维护租客信息表里的房间信息
        #roomList = self.roomList(self.get_url('fileRoomInfo'), 'RoomInfo') #获取已有房间清单
        if roomid not in lineText:
            messagebox.showwarning("告警", "此房间未出租！")
        else:
            df = pd.read_excel(self.url_fileTenantInfo, sheet_name='Tenant', engine='openpyxl', header=None)
            row_index = df.index[df[0] == roomid].tolist()[0]  # 获取需要删除房间索引
            df.loc[row_index, 0] = roomid
            df.loc[row_index, 1] = tenant
            df.loc[row_index, 2] = id
            df.loc[row_index, 3] = phone
            df.loc[row_index, 4] = checkintime
            df.loc[row_index, 5] = amount
            df.loc[row_index, 6] = deposit
            df.loc[row_index, 6] = deposit
            df.loc[row_index, 7] = warter1
            df.loc[row_index, 8] = warter2
            df.loc[row_index, 9] = electric1
            df.loc[row_index, 10] = electric2
            print(df)
            # 将DataFrame对象写入特定的工作表和行
            df.to_excel(self.url_fileTenantInfo, index=False, header=False, sheet_name='Tenant', startrow=0)
            self.frame2TenantShow() #重新展示租客户信息

    def deltenant(self): #删除租客信息
        rowNUM = self.enTroomid.get()
        s_la = self.setting.roomList(self.url_fileTenantInfo, 'Tenant')
        if rowNUM in s_la:
            i = s_la.index(rowNUM)
           # print(rowNUM, '已找到', i)
            row_data = rowNUM  # 要删除的行数据
            sheet_name = 'Tenant'  # 要删除数据的工作表名称
            self.setting.del_row_to_excel(self.url_fileTenantInfo, row_data, sheet_name)
            #self.canvas2.delete('all')
            self.frame2TenantShow() #重新展示房间
        else:
            messagebox.showwarning("告警", "此房间未出租！")

    def findtenant(self): #查找租客信息
        roomid = self.enTroomid.get()
        #print(self.setting.get_warterPrice())
        #print(self.setting.get_electricPrice())
        df = pd.read_excel(self.url_fileTenantInfo, sheet_name='Tenant', engine='openpyxl', header=None)
        try:
            row_index = df.index[df[0] == roomid].tolist()[0] #获取需要删除房间索引

        except Exception as e:
            messagebox.showwarning("提示", "此房间是否未出租！")
            print(f"发生了一个错误：{e}")
        else:
            tenant = df.loc[row_index, 1]
            id     = df.loc[row_index, 2]
            phone  = df.loc[row_index, 3]
            checkintime = df.loc[row_index, 4]
            amount = df.loc[row_index, 5]
            deposit = df.loc[row_index, 6]
            warter1 = df.loc[row_index, 7]
            warter2 = df.loc[row_index, 8]
            electric1 = df.loc[row_index, 9]
            electric2 = df.loc[row_index, 10]
            self.setting.reloadENT(self.enTtenant, tenant)
            self.setting.reloadENT(self.enTid, id)
            self.setting.reloadENT(self.enTphone, phone)
            #self.reloadENT(self.enTcheckintime, checkintime)
            #print(checkintime)
            self.enTcheckintime.set_date(datetime.strptime(checkintime, '%Y-%m-%d'))
            self.setting.reloadENT(self.enTamount, amount)
            self.setting.reloadENT(self.enTdeposit, deposit)
            self.setting.reloadENT(self.enTwarter1, warter1)
            self.setting.reloadENT(self.enTwarter2, warter2)
            self.setting.reloadENT(self.enTelectric1, electric1)
            self.setting.reloadENT(self.enTelectric2, electric2)
